import router from './router'
import store from './store'
import { getStore, setStore } from '@/utils/store'
import { Message } from 'element-ui'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import { getToken, removeToken } from '@/utils/auth' // get token from cookie
import getPageTitle from '@/utils/get-page-title'

NProgress.configure({ showSpinner: false }) // NProgress Configuration

/**
 * 验证当前跳转url是否有权限
 * @param {object} src  跳转url
 * @param {object} menuCode  菜单编码
 **/
const validPageUrlPermission = (src, toMenuCode, fromMenuCode) => {
  const frontUrl = src || ''
  // if (toPage.src && toPage.src.indexOf('/auth/oauth/authorize') > -1 && toPage.client_id && toPage.redirect_uri) {
  //   frontUrl = `${toPage.src}&client_id=${toPage.client_id}&redirect_uri=${encodeURIComponent(toPage.redirect_uri)}`
  // }
  if (!frontUrl) {
    return Promise.reject()
  }
  let p
  if (!toMenuCode) {
    p = store.dispatch('menu/getMenuCode', { path: src, fromMenuCode })
  } else {
    p = Promise.resolve(toMenuCode)
  }
  return p.then(menuCode => {
    const validParams = {
      frontUrl: frontUrl ? decodeURIComponent(frontUrl) : ''
    }
    if (menuCode) {
      validParams.menuCode = menuCode
    }
    return store.dispatch('user/validFrontUrl', validParams).then(() => {
      return toMenuCode || menuCode || fromMenuCode || ''
    })
  })
}

// 开发阶段不验证
// if (process.env.NODE_ENV === 'development') {
//   validPageUrlPermission = (src, toMenuCode, fromMenuCode) => {
//     return Promise.resolve(toMenuCode || fromMenuCode || '')
//   }
// }

const whiteList = ['/login', '/auth-redirect'] // no redirect whitelist

// const noMenuCodeList = ['HomePage', 'Transfer', 'Queue', 'Listen', 'CallOut']

router.beforeEach(async(to, from, next) => {
  // start progress bar
  NProgress.start()

  // set page title
  document.title = getPageTitle(to.meta.title)

  // determine whether the user has logged in
  const hasToken = getToken()
  if (hasToken) {
    // --------- 添加跳转登录开始
    if (to.query.username && to.query.password) {
      setStore({ name: 'login_loading', content: true, type: 'session' })
      removeToken()
      if (to.query.redirect_moduleCode) {
        setStore({ name: 'redirect_moduleCode', content: to.query.redirect_moduleCode })
      } else {
        setStore({ name: 'redirect_moduleCode', content: '' })
      }
      const otherLogin = {
        username: to.query.username,
        password: decodeURIComponent(to.query.password),
        code: '',
        randomStr: '',
        isAes: true
      }
      store.dispatch('user/login', otherLogin).then((res) => {
        const queryData = JSON.parse(JSON.stringify(to.query))
        delete queryData.username
        delete queryData.password
        delete queryData.redirect_url
        if (to.query.redirect_url) {
          const toPage = to.query.redirect_url
          validPageUrlPermission(toPage.src, toPage.menuCode).then(() => {
            next({ path: `/myiframe/urlPath?src=${to.query.redirect_url}`, query: queryData })
          }).catch(() => {
            next({ path: '/index' })
          })
        } else {
          next({ path: '/index' })
        }
      }).catch((err) => {
        console.log(err)
      })
    } else {
      setStore({ name: 'login_loading', content: false, type: 'session' })
    }
    // --------- 添加跳转登录结束
    if (to.path === '/login') {
      if (window.top !== window) {
        next(false)
        NProgress.done()
        return
      }
      // if is logged in, redirect to the home page
      next({ path: '/index' })
      NProgress.done()
    } else {
      // determine whether the user has obtained his permission roles through getInfo
      // const hasMenus = store.getters.menuList && store.getters.menuList.length > 0
      const hasRoles = store.getters.user && store.getters.user.userId
      if (hasRoles) {
        // 判断是否有菜单码
        if (/^\/redirect/.test(to.path)) {
          next()
        } else {
          validPageUrlPermission(to.path, to.query.menuCode, from.query.menuCode).then(menuCode => {
            if (!to.query.menuCode && menuCode) {
              to.query.menuCode = menuCode
              next({ ...to })
            } else {
              next()
            }
          }).catch(() => {
            next({ path: '/index' })
          })
        }
      } else {
        try {
          // get user info
          await store.dispatch('user/getInfo')
          let redirect_moduleCode = to.query.menuCode || ''
          if (getStore({ name: 'redirect_moduleCode' }) && getStore({ name: 'redirect_moduleCode' }) !== '') {
            redirect_moduleCode = getStore({ name: 'redirect_moduleCode' })
          }
          // 获取门户菜单
          await store.dispatch('menu/getPortalMenu', redirect_moduleCode).then(data => {
            const defualtMenu = data || ''

            store.dispatch('app/menuTypeTitle', { title: defualtMenu.menuName || '', icon: defualtMenu.icon || '' })
            store.dispatch('app/menuMoudel', defualtMenu.menuId || '')
            store.dispatch('app/homeUrl', defualtMenu.url || '')
            store.dispatch('menu/generateMenuTree', defualtMenu || []).then(result => {
              const pushRouter = [{ path: '*', redirect: '/404', hidden: true }]
              router.addRoutes(pushRouter)
            })
          }).catch((err) => {
            console.log(err)
          })
          // to.path === '/myiframe/urlPath' ? next({ to: to.fullPath, replace: true }) : next({ ...to, replace: true })
          if (to.path === '/myiframe/urlPath') {
            validPageUrlPermission(to.query.src, to.query.menuCode).then(() => {
              next({ to: to.fullPath, replace: true })
            }).catch(() => {
              next({ path: '/index' })
            })
          } else {
            validPageUrlPermission(to.path, to.query.menuCode, from.query.menuCode).then(() => {
              next({ ...to, replace: true })
            }).catch(() => {
              next({ path: '/index' })
            })
          }
          // hack method to ensure that addRoutes is complete
          // set the replace: true, so the navigation will not leave a history record
        } catch (error) {
          // remove token and go to login page to re-login
          await store.dispatch('user/resetToken')
          Message.error(error || 'Has Error')
          next(`/login?redirect=${to.fullPath}`)
          NProgress.done()
        }
      }
    }
  } else {
    if (window.top !== window) {
      next(false)
      NProgress.done()
      return
    }
    /* has no token*/
    if (whiteList.indexOf(to.path) !== -1) {
      // in the free login whitelist, go directly
      next()
    } else {
      // other pages that do not have permission to access are redirected to the login page.
      next(`/login?redirect=${to.fullPath}`)
      NProgress.done()
    }
  }
})

router.afterEach((to, from) => {
  // finish progress bar
  NProgress.done()
})
